﻿using Koala.Pro.Common;
using System.IO;
using System.Reflection;

namespace Koala.Pro.Helpers
{
    public static class WpfTypeHelper
    {
        public static Type LoadWpfType(string typeName)
        {
            if (typeName.IsNullOrEmpty())
            {
                return null;
            }
            try
            {
                string[] array = typeName.Split(',', ';');
                string name = array[0].Trim();
                string path = Assembly.GetExecutingAssembly().GetName().Name;
                if (array.Length > 1 && !array[1].Trim().IsNullOrWhiteSpace())
                {
                    path = array[1].Trim();
                }
                string text = ((array.Length > 2) ? array[2].ToLower() : "");
                if (text == "1")
                {
                    _ = 1;
                }
                else
                    _ = text == "dialog";
                string text2 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
                if (!text2.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && !text2.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
                {
                    string fileName = Path.GetFileName(text2);
                    string dir = Directory.GetParent(text2).FullName;
                    string[] array2 = new string[2] { ".dll", ".exe" }.SelectMany((string ext) => Directory.GetFiles(dir, fileName + ext, SearchOption.TopDirectoryOnly)).ToArray();
                    text2 = ((array2 != null) ? array2[0] : null);
                }
                Assembly assembly = Assembly.LoadFrom(text2);
                if (assembly != null)
                {
                    return assembly.GetType(name);
                }
            }
            catch (Exception ex)
            {
                LogTextHelper.Error($"加载模块【{typeName}】失败，请联系系统管理员。", ex);
            }
            return null;
        }
    }
}
